package common

import (
	"log"
	"os"
	"strconv"
	"strings"
	"bufio"
	"io"
)

const middle  string= "."

type Configure struct {
	  hmap map[string]string
}
var Conf *Configure
func init()  {
	var confpath string
	for _, v := range os.Args {
		if i := strings.Index(v, "conf:"); i > 0 {
			v = v[i+5:]
			confpath = v
		}
	}
	if len(confpath) > 0 {
		c, err := LoadConf(confpath)
		if err != nil {
			log.Fatal(err)
			return
		}
		c.hmap["defualt.confpath"]=confpath
		c.hmap["defualt.ospath"]=confpath
		Conf=c
	}
}


func  LoadConf(path string)(cfg *Configure, err error) {
	var strcet1 string=""
	cfg = new(Configure)
    cfg.hmap=make(map[string]string,20)

	f, err := os.Open(path)
	if err != nil {
		return cfg, err
	}
	defer f.Close()
	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
		}
		s := strings.TrimSpace(string(b))
		if strings.Index(s, "#") == 0 {
			continue
		}
		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			strcet1 = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		index := strings.Index(s, ":")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}
		if len(strcet1) > 0 {
			frist = strcet1 + middle + frist
		}
		cfg.hmap[frist] = strings.TrimSpace(second)
	}
	return cfg,nil
}
func (this *Configure) Read_String(key string) string {
	v, found := this.hmap[key]
	if !found {
		log.Fatalf("key:%s non exist", key)
	}
	return v
}
func (this *Configure) Read_Int64(key string) int64{
	v, found := this.hmap[key]
	if !found {
		log.Fatalf("key:%s non exist", key)
	}
	n, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		log.Fatalf("key:%s is't integer", key)
	}
	return n
}

